package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	UserDao userDao;
	@Autowired
	MenuDao menuDao;

	@Override
	public boolean login(String username, String password) {
		System.out.println("service_provide...u:"+username+" p:"+password);
		return "admin".equals(username) && "123".equals(password);
	}

	@Override
	public SysUser findByUsername(String username) {
		return userDao.findByUsername(username);
	}

	@Override
	public List<Map<String, Object>> getUserMenu(String username) {
		//根据用户名查询出来用户信息
		SysUser sysUser= userDao.getUserMenu(username);
		//创建父菜单集合
		List<Menu> parentList=new ArrayList<>();
		//遍历用户的角色信息,根据角色信息获取菜单信息
		for (Role role : sysUser.getRoles()) {
			for (Menu menu : role.getMenus()) {
				//根据用户的ParentMenuId来判断父菜单
				if (menu.getParentMenuId()==null){
					//根据父菜单的id查询子菜单
					List<Menu> childList=menuDao.findChildById(menu.getId());
					//将子菜单信息存进父菜单中
                    menu.setChildren(childList);
					parentList.add(menu);
				}
			}
		}
		List<Map<String,Object>> menuList=new ArrayList<>();
		//遍历父菜单
		for (Menu parentMenu : parentList) {
			//创建Map集合存储父菜单信息
			Map<String,Object> parentMap=new HashMap<>();
			parentMap.put("path",parentMenu.getPath());
			parentMap.put("title",parentMenu.getName());
			parentMap.put("icon",parentMenu.getIcon());
			//创建List集合存储子菜单信息
			List<Map<String,Object>> childList=new ArrayList<>();
			//遍历父菜单的子菜单
			for (Menu child : parentMenu.getChildren()) {
				//创建map存储子菜单的信息
				 Map<String,Object> childMap=new HashMap<>();
			     childMap.put("path",child.getPath());
			     childMap.put("title",child.getName());
				 childMap.put("linkUrl",child.getLinkUrl());
				 childMap.put("children","NUll");
				 childList.add(childMap);
			}
			parentMap.put("children",childList);
            menuList.add(parentMap);
		}
		System.out.println("menuList==="+menuList.toString());

		return menuList;
	}
}